<?php

namespace app\api\controller;

//操作此类的接口必须带有usertoken
use think\Db;
use think\Exception;
use WebGeeker\Validation\Validation;

class User extends UserBase
{

    //关注&取消关注
    public function attention()
    {
        //获取作者的user_unique
        //author_id 就是用户表中的user_unique
        try {
// 验证（如果验证不通过，会抛出异常）
            Validation::validate($_GET, [
                "author_id" => "Required|Str|StrLenGe:1",  // 参数"count"是必需的且取值在 1 - 200 之间
                "status" => "Required|IntIn:0,1|>>>:status参数值不正确"
            ]);

            //作者的标识
            $user_unique = $_GET['author_id'];

            //操作的状态
            $status = (int)$_GET['status'];

            //判断当前作者是否存在
            $user_result = Db::name('user')->where(['user_unique' => $user_unique])->value('user_id');

            if (!$user_result) {
                throw new Exception('作者不存在');
            }

            if ($user_result == $this->user_id) {
                throw new Exception('自己不能关注自己');
            }

            //获取当前关注的状态
            $user_attention_mongo_obj = $this->mongo_obj->name('user_attention_record');

            $attention_result = $user_attention_mongo_obj->where(['follower_user_id' => $this->user_id, 'by_follower_user_unique' => $user_unique])->find();

            if ($attention_result) {

                switch ($attention_result['status']) {
                    case 1:
                        if ($status == 1) {
                            throw new Exception('非法关注');
                        } else {
                            $msg = '取消关注';
                            $type = 'cancleAttentionFeedHandel';
                        }
                        break;

                    case 0:
                        if ($status == 0) {
                            throw new Exception('非法取消关注');
                        } else {
                            $type = 'attentionFeedHandle';
                            $msg = '关注';
                        }
                        break;
                }

                $result = $user_attention_mongo_obj->where(['id' => $attention_result['id']])->update(['status' => $status, 'attention_time' => time()]);
            } else {
                //数据不存在
                switch ($status) {
                    case 0:
                        throw new Exception('非法取消关注');
                        break;

                    case 1:
                        $msg = '关注';
                        $type = 'attentionFeedHandle';
                        break;
                }
                $result = $user_attention_mongo_obj->insertGetId(['follower_user_id' => $this->user_id,
                    'by_follower_user_unique' => $user_unique, 'status' => $status, 'attention_time' => time()]);

            }

            if ($result) {

                add_queue('app\queueHandle\News', 'News',
                    ['follower_user_id' => $this->user_id, 'by_follower_user_unique' => $user_unique, 'type' => $type]);

                successBack([], $msg . '成功');
            } else {
                throw new Exception('关注失败', 1);
            }
        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }

    //对文章直接评论
    public function remarkNews()
    {
        try {

            Validation::validate($_GET, [
                "item_id" => "Required|Str|StrLenGe:1",
                "remark_content" => "Required|Str|StrLenGe:1"
            ]);

            //文章的item_id
            $item_id = $_GET['item_id'];

            //文章的评论(去除左右的空格)
            $remark_content = trim($_GET['remark_content']);

            //文章的mongo对象
            $item_mongo_obj = $this->mongo_obj->name('item');

            isNewsExist($item_id, $item_mongo_obj);

            $this->insertRemarkData($item_id, 1, 0, 0, $remark_content);

        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }

    //回复评论
    public function replyRemark()
    {
        try {

            Validation::validate($_GET, [
                "item_id" => "Required|Str|StrLenGe:1",
                "remark_content" => "Required|Str|StrLenGe:1",
                "remark_id" => "Required|Str|StrLenGe:1",
            ]);

            //文章的id
            $item_id = $_GET['item_id'];

            //评论的内容
            $remark_content = trim($_GET['remark_content']);

            //被回复评论的id
            $remark_id = $_GET['remark_id'];

            //判断当前评论是不是存在,是不是属于这个文章
            //评论的item_remark
            $item_remark_obj = $this->mongo_obj->name('item_remark');

            $result = $item_remark_obj->where(['item_id' => $item_id, 'id' => $remark_id])->field('type,belong_remark_id')->find();

            if (!$result) {
                throw new Exception('数据不存在');
            }

            //评论的类型
            switch ($result['type']) {
                case 1:
                    $type = 2;
                    break;
                case 2:
                    $type = 3;
                    break;
                case 3:
                    $type = 3;
                    break;
            }

            //属于哪一个一级评论
            if ($result['belong_remark_id'] == 0) {
                $belong_remark_id = $remark_id;
            } else {
                $belong_remark_id = $result['belong_remark_id'];
            }

            $this->insertRemarkData($item_id, $type, $belong_remark_id, $remark_id, $remark_content);

        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }

    //插入评论的公共的存储数据,$item_id 是文章的id,$type 评论的类型,$belong_remark_id 属于哪一个一级评论
    //parent_id 被回复评论的id,$remark_content 评论的内容 ,$by_remark_nick_name 被评论人的昵称,$by_remark_head_img 被评论人的头像
    private function insertRemarkData($item_id, $type, $belong_remark_id, $parent_id, $remark_content, $by_remark_nick_name = '', $by_remark_head_img = '')
    {
        //一级评论的数数据
        $addData = [];

        //评论人的id
        $addData['user_id'] = $this->user_id;

        $addData['user_unique'] = $this->user_unique;

        //被评论的文章id
        $addData['item_id'] = $item_id;

        //评论的类型
        $addData['type'] = $type;


        //评论的时间
        $addData['remark_time'] = time();

        //属于哪一个一级评论
        $addData['belong_remark_id'] = $belong_remark_id;

        //父评论(被回复的评论id)
        $addData['parent_id'] = $parent_id;

        //该评论的点赞数
        $addData['remark_favour_numbers'] = 0;

        //该评论被回复的数
        $addData['remark_by_numbers'] = 0;

        //评论人的昵称
        $addData['remark_nick_name'] = $this->nick_name;

        //评论人的头像
        $addData['remark_head_img'] = $this->head_img;

        //文章的评论内容
        $addData['remark_content'] = $remark_content;

        //文章的热度
        $addData['remark_heat'] = 0;

        //被评论人的昵称
        //$addData['by_remark_nick_name'] = $by_remark_nick_name;

        //被评论人的头像
        //$addData['by_remark_head_img'] = $by_remark_head_img;

        //评论的点赞数
        $addData['remark_favour_numbers'] = 0;

        //评论的唯一性计数
        $addData['remark_count'] = getMid('item_remark');

        //插入数据
        //评论的 集合对象
        $item_remakr_obj = $this->mongo_obj->name('item_remark');

        $result = $item_remakr_obj->insertGetId($addData);

        if ($result) {

            //评论成功,给item的remark_numbers加1

            $this->mongo_obj->name('item')->where(['id' => $item_id])->setInc('remark_numbers');

            //回复评论时进行热度计算
            if ($parent_id != 0) {
                //更新被回复的数量
                $update_remark_by_numbers_result = $this->mongo_obj->name('item_remark')
                    ->where(['id' => $parent_id])
                    ->setInc('remark_by_numbers');

                if ($update_remark_by_numbers_result) {
                    //更新成功,异步计算热度
                    add_queue('app\queueHandle\News', 'News',
                        ['remark_id' => $parent_id, 'type' => 'newsHeatCountHandle']);
                }
            }

            successBack(['id' => $result], '评论成功');

        } else {
            throw new Exception('评论失败', 1);
        }

    }

    //文章/视频收藏
    public function itemCollet()
    {
        try {
            Validation::validate($_GET, [
                "item_id" => "Required|Str|StrLenGe:1",
                'collect_status' => "Required|IntIn:0,1"
            ]);

            //判断item_id 是不是存在

            $item_id = $_GET['item_id'];

            $this->mongo_obj->name('item')->where(['id' => $item_id])->findOrFail();

            //item_collect_record，查看是不是已经收藏了
            $item_collect_record_obj = $this->mongo_obj->name('item_collect_record');

            //查看当前是不是已经收藏了
            $item_collect_record_result = $item_collect_record_obj
                ->where(['item_id' => $item_id,
                    'collect_user_id' => $this->user_id,
                ])
                ->field('collect_status')
                ->find();

            $collect_status = (int)$_GET['collect_status'];

            if ($item_collect_record_result) {
                if ($item_collect_record_result['collect_status'] == 1) {
                    switch ($collect_status) {
                        case 1:
                            throw new Exception('非法收藏');
                            break;
                        case 0:
                            $msg = '取消收藏';
                            break;
                    }
                } elseif ($item_collect_record_result['collect_status'] == 0) {
                    switch ($collect_status) {
                        case 1:
                            $msg = '收藏';
                            break;
                        case 0:
                            throw new Exception('非法取消收藏');
                            break;
                    }
                } else {
                    throw new Exception('数据库数据不正确');
                }


                $result = $item_collect_record_obj
                    ->where(['item_id' => $item_id,
                        'collect_user_id' => $this->user_id])
                    ->update(['collect_status' => $collect_status, 'collect_time' => time()]);

            } else {
                //从未点赞过当前文章
                switch ($collect_status) {
                    case 1:
                        $msg = '收藏';
                        break;

                    case 0:
                        throw new Exception('非法取消收藏');
                        break;
                }

                $result = $item_collect_record_obj
                    ->insertGetId(['item_id' => $item_id,
                        'collect_user_id' => $this->user_id, 'collect_status' => $collect_status, 'collect_time' => time()]);
            }

            if ($result) {
                successBack([], $msg . '成功');
            } else {
                throw new Exception($msg . '失败', 1);
            }
        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }
}